#!/usr/bin/env python
from django.core.management import execute_manager
try:
    import settings # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)

if __name__ == "__main__":
    import sys
    import os
    
    if settings.DEBUG and len(sys.argv) > 1 and sys.argv[1] == "xrunserver":
        if len(sys.argv) >= 3:
            all = sys.argv[2].split(':')
            port = all[-1]
            host = '' if len(all) == 1 else all[0]
        else:
            port = '8000'
            host = ''

        from django.core.handlers.wsgi import WSGIHandler
        app = WSGIHandler()
        os.environ["DJANGO_SETTINGS_MODULE"] = "settings"

        import PyCaduceus
        import atexit

        server = PyCaduceus.CreateWebServer(app, "/", int(port), host)
        server.setServiceOption('/', 'info', '1')
        server.loadService('/static', 'FileService')
        server.setServiceOption('/static', 'directory', settings.MEDIA_ROOT)
        # Admin media.
        import django
        p = django.__path__[0] + '/contrib/admin/media'
        server.loadService(settings.ADMIN_MEDIA_PREFIX, 'FileService')
        server.setServiceOption(settings.ADMIN_MEDIA_PREFIX, 'directory', p)

        atexit.register(server.stop)
        server.start()
        
        import time
        while True:
            time.sleep(100)
    else:
        execute_manager(settings)
